package jdbc;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSelect {

    public static void main(String[] args) throws SQLException {
        //创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java105?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("721125");

        //与数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //构造SQL语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);


        //执行sql
        ResultSet resultSet = statement.executeQuery();

        //遍历结果集
        while(resultSet.next()) {

            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            System.out.println("id = " + id + ", name = " + name);


        }
        //释放资源
        resultSet.close();
        statement.close();
        connection.close();



    }
}
